<template>

    <el-dialog
        :title="!dataForm.id ? '新增' : '修改'"
        :close-on-click-modal="false"
        :visible.sync="visible">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
                 label-width="80px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="dataForm.title" placeholder="标题" maxlength="15"
                          show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="catIds">
                <el-cascader
                    v-model="dataForm.catIds"
                    :options="catList"
                    :props="{ expandTrigger: 'hover' ,value:'id',label:'name'}">
                </el-cascader>
            </el-form-item>
            <el-form-item label="是否展示" prop="isShow">
                <el-switch
                    v-model="dataForm.isShow"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                </el-switch>
            </el-form-item>
            <el-form-item label="浏览次数" prop="watchTime">
                <el-input-number v-model="dataForm.watchTime" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
            <el-form-item label="标签ID" prop="labelChooseList">
                <el-select
                    v-model="dataForm.labelChooseList"
                    multiple
                    filterable
                    allow-create
                    placeholder="请选择">
                    <el-option
                        v-for="item in labelList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>

            </el-form-item>
            <el-form-item label="文章图片" prop="showImg">
                <el-input v-model="dataForm.showImg" placeholder="文章图片路径" :disabled="imgInputDisabled"></el-input>
                <el-upload
                    class="upload-demo"
                    :action="uploadUrl"
                    :data="signData"
                    :headers="headers"
                    :multiple="false"
                    :limit="1"
                    :before-upload="beforeUpload"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                    :file-list="fileList"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="发布地点" prop="addrInfo">
                <el-input v-model="dataForm.provincial+'-'+dataForm.urban" placeholder="发布地点信息" disabled></el-input>
                <Map :height="200"
                     @initlivepositionievent="initlivePositionEvent"
                     @changelivepositionevent="livePositionEvent"
                     @markerclickevent="livePositionEvent"
                     :address-init-info-arr="[{lng:dataForm.lng,lat:dataForm.lat,addr:dataForm.addr,}]"
                     ref="articleMap"
                ></Map>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
        </span>
    </el-dialog>

</template>

<script>

    import {getUUID} from '../../../utils';
    import Cookies from 'js-cookie';
    import Map from '@/components/Map';

    export default {
        data() {
            return {
                activeNames: ['1'],
                visible: false,
                dataForm: {
                    id: 0,
                    author: '',
                    title: '',
                    catId: 0,
                    catIds: [],
                    isShow: 0,
                    watchTime: 0,
                    labelId: '',
                    labelChooseList: [],
                    delFlag: 1,
                    showImg: '',
                    addr: '',
                    lng: '',
                    lat: '',
                    provincial: '',
                    urban: '',
                    areas: ''
                },
                dataRule: {
                    author: [
                        {required: true, message: '作者不能为空', trigger: 'blur'}
                    ],
                    title: [
                        {required: true, message: '标题不能为空', trigger: 'blur'}
                    ],
                    catIds: [
                        {required: true, message: '类型不能为空', trigger: 'blur'}
                    ],
                    isShow: [
                        {required: true, message: '是否展示不能为空', trigger: 'blur'}
                    ],
                    watchTime: [
                        {required: true, message: '浏览次数不能为空', trigger: 'blur'}
                    ],
                    labelChooseList: [
                        {required: true, message: '标签ID不能为空', trigger: 'blur'}
                    ],
                    showImg: [
                        {required: true, message: '文章展示图片不能为空', trigger: 'blur'}
                    ]
                },
                signData: {
                    policy: '',
                    signature: '',
                    key: '',
                    ossaccessKeyId: '',
                    accessKeyId: '',
                    dir: '',
                    host: ''
                },
                headers: {'token': ''},
                // fileList: [ {name: 'food.jpeg',  url: 'url'}]
                fileList: [],
                uploadUrl: this.global.fileUrl, //上传文件路径
                imgInputDisabled: false, //是否支持自定义输入，在上传选择后不允许再次输出

                //富文本编辑点
                summerNoteVal: '',

                labelList: null,
                catList: null

            };
        },
        components: {Map},
        computed: {
            alias() {
                return this.$store.state.common.userInfo.alias;
            }
        },
        methods: {
            init(id) {
                this.fileList = [];
                this.summerNoteVal = '';
                this.dataForm.id = id || 0;
                this.visible = true;

                this.getLabelList();
                this.getCatList();

                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields();
                    if (this.dataForm.id) {
                        this.$api.Info.info(this.dataForm.id).then((data) => {
                            if (data && data.code === 0) {
                                this.dataForm.author = data.info.author;
                                this.dataForm.title = data.info.title;
                                this.dataForm.catId = data.info.catId;
                                this.dataForm.isShow = data.info.isShow;
                                this.dataForm.watchTime = data.info.watchTime;
                                this.dataForm.labelId = data.info.labelId;
                                this.dataForm.createBy = data.info.createBy;
                                this.dataForm.createTime = data.info.createTime;
                                this.dataForm.lastUpdateBy = data.info.lastUpdateBy;
                                this.dataForm.lastUpdateTime = data.info.lastUpdateTime;
                                this.dataForm.delFlag = data.info.delFlag;
                                this.dataForm.showImg = data.info.showImg;

                                //初始化标签数组
                                this.dataForm.labelChooseList = data.info.labelId.split(',').map(label => {
                                    return parseInt(label);
                                });
                                // this.fileList.push({name: "", url: data.info.showImg}); //初始化图片

                                if(data.info.lng && data.info.lat) {

                                    //有实际坐标，赋予初始
                                    this.dataForm.addr = data.info.addr;
                                    this.dataForm.lng = data.info.lng;
                                    this.dataForm.lat = data.info.lat;
                                    this.dataForm.provincial = data.info.provincial;
                                    this.dataForm.urban = data.info.urban;
                                    this.dataForm.areas = data.info.areas;

                                    this.$nextTick(() => {
                                        this.$refs['articleMap'].resetMakers();
                                    });
                                }

                                //重置分类数组 用于级联展示
                                this.getCatIds();
                            }
                        });
                    } else {
                        this.dataForm.author = this.alias;
                    }
                });

            },

            //重置分类数组 用于级联展示
            getCatIds() {

                let _self = this;
                const key = _self.dataForm.catId;
                let arrTemp = []; //中间记录使用
                exec(_self.catList);

                function exec(catListChidren) {
                    //没数据 - 网络获取延迟 - 延时遍历
                    if (!catListChidren) {
                        setTimeout(() => {
                            exec(_self.catList);
                        }, 100);
                        return;
                    }
                    catListChidren.map(cat => {
                        arrTemp.push(cat.id);
                        if (cat.children && cat.children.length > 0) {
                            exec(cat.children);
                            arrTemp.pop();
                        } else {
                            if (cat.id == key) {
                                _self.dataForm.catIds = [...arrTemp];
                            } else {
                                arrTemp.pop();
                            }
                        }
                    });
                }
            },

            //获取标签信息
            getLabelList() {
                if (!this.labelList) {
                    this.$api.Label.listAll().then((data) => {
                        if (data && data.code === 0) {
                            this.labelList = data.labelList;
                        }
                    });
                }
            },

            //获取分类信息
            getCatList() {
                if (!this.catList) {
                    this.$api.Category.listTree().then((data) => {
                        if (data && data.code === 0) {
                            this.catList = data.categoryTreeList;
                        }
                    });
                }
            },

            // 表单提交
            dataFormSubmit() {
                var contentNew;
                let _self = this;
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {

                        exec();

                        async function exec() {
                            saveInfo();
                        }

                        //上传数据
                        function saveInfo() {
                            console.log('/article/article/ -s');

                            let data = {
                                'id': _self.dataForm.id || undefined,
                                'author': _self.dataForm.author,
                                'catId': _self.dataForm.catIds[_self.dataForm.catIds.length - 1],
                                'title': _self.dataForm.title,
                                // 'content': _self.dataForm.content,
                                'isShow': _self.dataForm.isShow,
                                'watchTime': _self.dataForm.watchTime,
                                'labelId': _self.dataForm.labelChooseList.join(','),
                                'createBy': _self.dataForm.createBy,
                                'createTime': _self.dataForm.createTime,
                                'lastUpdateBy': _self.dataForm.lastUpdateBy,
                                'lastUpdateTime': _self.dataForm.lastUpdateTime,
                                'delFlag': _self.dataForm.delFlag,
                                'showImg': _self.dataForm.showImg,
                                'addr': _self.dataForm.addr,
                                'lng': _self.dataForm.lng,
                                'lat': _self.dataForm.lat,
                                'provincial': _self.dataForm.provincial,
                                'urban': _self.dataForm.urban,
                                'areas': _self.dataForm.areas,
                            };
                            let resultAction;
                            if (!_self.dataForm.id) {
                                resultAction = _self.$api.Info.save(data);
                            } else {
                                resultAction = _self.$api.Info.update(data);
                            }

                            resultAction.then((data) => {
                                if (data && data.code === 0) {
                                    _self.$message({
                                        message: '操作成功',
                                        type: 'success',
                                        duration: 1500,
                                        onClose: () => {
                                            _self.visible = false;
                                            _self.$emit('refreshDataList');
                                        }
                                    });
                                } else {
                                    _self.$message.error(data.msg);
                                }
                            });
                        }

                    }
                });
            },

            //上传前操作-获取签名
            beforeUpload(file) {
                console.log(file);
                let _self = this;
                let filename = file.name;

                return new Promise((resolve, reject) => {
                    this.$api.File.ossPolicy().then((data) => {
                        if (data && data.code === 0) {
                            console.log('签名返回数据' + data.data);

                            _self.signData.ossaccessKeyId = data.data.accessid;
                            _self.signData.accessKeyId = data.data.accessid;
                            _self.signData.policy = data.data.policy;
                            _self.signData.signature = data.data.signature;
                            _self.signData.key = data.data.dir + getUUID() + `_${filename}`;
                            _self.signData.dir = data.data.dir;
                            _self.signData.host = data.data.host;
                            _self.signData.expire = data.data.expire;

                            let token = Cookies.get('token');
                            _self.headers = {'token': token};

                            resolve();
                        } else {
                            this.$message.error(data.msg);
                            reject();
                        }
                    });

                });

                console.log('this.signData');
                console.log(this.signData);
            },
            handleRemove(file, fileList) {
                console.log('handleRemove');
                console.log(file, fileList);
            },
            handleSuccess(response, file, fileList) {
                this.dataForm.showImg = this.uploadUrl + '/' + this.signData.key;
                this.imgInputDisabled = true;
            },

            getContent() {
                this.dialogVisible = true;
                this.ue.ready(() => {
                    this.ueContent = this.ue.getContent();
                });
            },

            //地图位置获取事件
            initlivePositionEvent(liveAddress) {
                if(!(this.dataForm.lng && this.dataForm.lat)) {
                    this.livePositionEvent(liveAddress);
                }
            },
            livePositionEvent(liveAddress) {
                this.dataForm.addr = liveAddress.addressDetail;
                this.dataForm.lng = liveAddress.lng;
                this.dataForm.lat = liveAddress.lat;
                this.dataForm.provincial = liveAddress.province;
                this.dataForm.urban = liveAddress.city;
                this.dataForm.areas = liveAddress.district;
            }

        }
    };
</script>
